<!--
 * @Description: 
 * @Date: 2023-04-10 20:31:55
 * @LastEditTime: 2023-04-10 23:08:52
 * @Author: Black
 * @FilePath: \store_admin\src\views\category\components\GoodsDrawer.vue
-->
<template>
  <FormDrawer ref="formDrawerRef" title="推荐商品" @submit="handleConnect" confirmText="关联" size="50%">
    <el-table :data="tableData" border stripe style="width:100%;">
      <el-table-column prop="goods_id" label="ID" width="100" align="center" />
      <el-table-column label="商品封面" width="240" align="center">
        <template #default="{ row }">
          <el-image :src="row.cover" fit="cover" :lazy="true" style="width: 64px; height: 64px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="200" align="center" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="{ row }">
          <el-popconfirm title="是否要删除该记录？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete(row)"
            width="200px">
            <template #reference>
              <el-button type="primary" text size="small" :loading="row.loading">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </FormDrawer>

  <ChooseGoods ref="ChooseGoodsRef"></ChooseGoods>
</template>

<script setup>
import { ref } from 'vue';
import FormDrawer from '~/components/FormDrawer.vue';
import {
  getCategoryGoods,
  deleteCategoryGoods,
  connectCategoryGoods
} from '~/api/category.js';
import { toast } from '~/composables/util.js'
import ChooseGoods from '~/components/ChooseGoods.vue';

const formDrawerRef = ref(null)
const category_id = ref(0)
const tableData = ref([])

const open = (item) => {
  category_id.value = item.id
  item.goodsDrawerLoading = true
  getData().then(res => formDrawerRef.value.open())
    .finally(() => {
      item.goodsDrawerLoading = false
    })
}

function getData() {
  return getCategoryGoods(category_id.value)
    .then(res => {
      tableData.value = res.map(o => {
        o.loading = false
        return o
      })
    })
}

const handleDelete = (row) => {
  row.loading = true
  deleteCategoryGoods(row.id).then(res => {
    toast("删除成功")
    getData()
  })
}

const ChooseGoodsRef = ref(null)
const handleConnect = () => {
  ChooseGoodsRef.value.open((goods_ids) => {
    formDrawerRef.value.showLoading()
    connectCategoryGoods({
      category_id: category_id.value,
      goods_ids
    }).then(res => {
      getData()
      toast("关联成功")
    }).finally(() => {
      formDrawerRef.value.hideLoading()
    })
  })
}

defineExpose({
  open
})
</script>

<style scoped></style>